//
//  AVAsset+STTools.m
//  VideoCollage
//
//  Created by Mac on 2018/6/20.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "AVAsset+STTools.h"

@implementation AVAsset (STTools)
- (AVAssetTrack *)firstVideoTrack {
    
    NSArray *tracks = [self tracksWithMediaType:AVMediaTypeVideo];
    
    return [tracks firstObject];
    
}


- (AVAssetTrack *)firstAudioTrack {
    
    NSArray *tracks = [self tracksWithMediaType:AVMediaTypeAudio];
    
    return [tracks firstObject];
    
}

- (void)whenProperties:(NSArray *)names areReadyDo:(void (^)(void))block {
    
   __block NSArray * realNames = names;
    [self loadValuesAsynchronouslyForKeys:realNames completionHandler:^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *error = nil;
            NSMutableArray *pendingNames;
            for (NSString *name in names){
                AVKeyValueStatus status = [self statusOfValueForKey:name error:&error];
                switch (status) {
                    case AVKeyValueStatusLoaded:
                        DDLogInfo(@"%@准备好了",self);
                        break;
                    case AVKeyValueStatusFailed:
                        DDLogInfo(@"%@准备失败",self);
                        break;
                    default:
                    if (pendingNames ==  nil) {
                        pendingNames = [NSMutableArray array];
                    }
                    [pendingNames addObject:name];
            }
        }
            if (pendingNames == nil) {
                block();
            } else {
                [self whenProperties:pendingNames areReadyDo:block];
            }
        });
    }];
    
}
@end
